package com.jgads.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.anythink.core.api.ATInitMediation;
import com.anythink.core.api.MediationInitCallback;
import com.junion.JgAds;
import com.junion.config.JUnionCustomController;
import com.junion.config.JUnionInitConfig;
import com.junion.listener.JUnionInitListener;
import com.junion.ad.error.JUnionError;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class InitManager extends ATInitMediation {
    private static InitManager sInstance;
    private Handler mHandler;
    private boolean mIsOpenDirectDownload;

    private boolean mHasInit;
    private AtomicBoolean mIsIniting;
    private List<MediationInitCallback> mListeners;
    private final Object mLock = new Object();

    private InitManager() {
        mHandler = new Handler(Looper.getMainLooper());
        mIsOpenDirectDownload = false;
        mIsIniting = new AtomicBoolean(false);
    }

    public synchronized static InitManager getInstance() {
        if (sInstance == null) {
            sInstance = new InitManager();
        }
        return sInstance;
    }


    @Override
    public synchronized void initSDK(Context context, Map<String, Object> serviceExtras, MediationInitCallback mediationInitCallback) {
        initJGSDK(context, serviceExtras, mediationInitCallback);
    }


    public void initJGSDK(final Context context, Map<String, Object> serviceExtras, final MediationInitCallback callback) {

        if (mHasInit) {
            if (callback != null) {
                callback.onSuccess();
            }
            return;
        }

        synchronized (mLock) {

            if (mIsIniting.get()) {
                if (callback != null) {
                    mListeners.add(callback);
                }
                return;
            }

            if (mListeners == null) {
                mListeners = new ArrayList<>();
            }

            mIsIniting.set(true);
        }

        if (!serviceExtras.containsKey("app_id")) {
            callback.onFail("app_id is null");
            return;
        }

        if (!serviceExtras.containsKey("slot_id")) {
            callback.onFail("slot_id is null");
            return;
        }

        final String appId = (String) serviceExtras.get("app_id");

        if (callback != null) {
            mListeners.add(callback);
        }

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                initJGAdsAd(context, appId);
            }
        });
    }

    private void initJGAdsAd(Context context, String appId) {

//        Log.d("JGAdsLog", "isDebug: " + JGAdsATInitManager.getInstance().isDebug());
//        Log.d("JGAdsLog", "isAgreePrivacyStrategy: " + JGAdsATInitManager.getInstance().isAgreePrivacyStrategy());
//        Log.d("JGAdsLog", "isCanUseWifiState: " + JGAdsATInitManager.getInstance().isCanUseWifiState());
//        Log.d("JGAdsLog", "isCanUsePhoneState: " + JGAdsATInitManager.getInstance().isCanUsePhoneState());
//        Log.d("JGAdsLog", "isCanUseLocation: " + JGAdsATInitManager.getInstance().isCanUseLocation());
//        Log.d("JGAdsLog", "getOaid: " + JGAdsATInitManager.getInstance().getOaid());
//        Log.d("JGAdsLog", "geAndroidId: " + JGAdsATInitManager.getInstance().geAndroidId());
//        Log.d("JGAdsLog", "getMac: " + JGAdsATInitManager.getInstance().getMac());
//        Log.d("JGAdsLog", "getImei: " + JGAdsATInitManager.getInstance().getImei());

        try {
            JgAds.getInstance().init(context, new JUnionInitConfig.Builder()
                    .appId(appId)
                    .debug(JGAdsATInitManager.getInstance().isDebug())
                    .agreePrivacyStrategy(JGAdsATInitManager.getInstance().isAgreePrivacyStrategy())
                    .isCanUseWifiState(JGAdsATInitManager.getInstance().isCanUseWifiState())
                    .isCanUsePhoneState(JGAdsATInitManager.getInstance().isCanUsePhoneState())
                    .isCanUseLocation(JGAdsATInitManager.getInstance().isCanUseLocation())
                    .setCustomController(new JUnionCustomController() {
                        @Override
                        public String getDevOaid() {
                            return JGAdsATInitManager.getInstance().getOaid();
                        }

                        @Override
                        public String getDevVaid() {
                            return JGAdsATInitManager.getInstance().getVaid();
                        }

                        @Override
                        public String getAndroidId() {
                            return JGAdsATInitManager.getInstance().geAndroidId();
                        }

                        @Override
                        public String getMacAddress() {
                            return JGAdsATInitManager.getInstance().getMac();
                        }

                        @Override
                        public String getDevImei() {
                            return JGAdsATInitManager.getInstance().getImei();
                        }
                    })
                    .build(), new JUnionInitListener() {
                @Override
                public void onInitFinished() {
                    mHasInit = true;
                    callbackResult(true, null, null);
                }

                @Override
                public void onInitFailed(JUnionError error) {
                    callbackResult(false, error.getCode() + "", error.getError());
                }
            });
        } catch (Throwable e) {
            callbackResult(false, "", e.getMessage());
        }
    }

    private void callbackResult(boolean success, String errorCode, String errorMsg) {
        synchronized (mLock) {
            int size = mListeners.size();
            MediationInitCallback initListener;
            for (int i = 0; i < size; i++) {
                initListener = mListeners.get(i);
                if (initListener != null) {
                    if (success) {
                        initListener.onSuccess();
                    } else {
                        initListener.onFail(errorCode + ":" + errorMsg);
                    }
                }
            }
            mListeners.clear();

            mIsIniting.set(false);
        }
    }

    @Override
    public String getNetworkName() {
        return "JGAds";
    }


    @Override
    public String getNetworkVersion() {
        try {
            return JgAds.getInstance().getSdkVersion();
        } catch (Throwable e) {

        }
        return "";
    }
}
